package com.king.run.base;

import android.Manifest;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.StringRes;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.FragmentActivity;
import android.support.v4.content.ContextCompat;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.king.run.R;
import com.king.run.util.ActivityManager;
import com.king.run.util.CheckNetwork;
import com.king.run.util.PrefName;
import com.king.run.util.PreferencesUtils;
import com.king.run.util.StringUtil;

import org.json.JSONObject;
import org.xutils.common.Callback;
import org.xutils.http.HttpMethod;
import org.xutils.http.RequestParams;
import org.xutils.x;

import java.util.Map;


public class BaseActivity extends FragmentActivity {
    public Context context;
    private ProgressDialog progressDialog;
    public ImageView title_iv_back;
    public TextView title_tv_title, title_tv_right, title_tv_back;
    public RelativeLayout title_relate_layout;
    public ImageView title_iv_right;
    private String type;
    public static Activity topActivity;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        x.view().inject(this);
        ActivityManager.getInstance().pushOneActivity(this);
        context = this;
        initTitleBar();
//        init();
    }

    @Override
    protected void onResume() {
        topActivity = this;
        super.onResume();
    }

    private void initTitleBar() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Window window = getWindow();
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS
                    | WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(Color.TRANSPARENT);
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            Window window = getWindow();
            window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }
    }

    public void init() {
        DisplayMetrics dm = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(dm);
        int screenWidthDip = dm.widthPixels; // 屏幕宽
        int screenHeightDip = dm.heightPixels; // 屏幕宽
        PreferencesUtils.putInt(BaseActivity.this, PrefName.SCREEN_HEIGHT, screenHeightDip);
        PreferencesUtils.putInt(BaseActivity.this, PrefName.SCREEN_WIDTH, screenWidthDip);
        title_iv_back = (ImageView) findViewById(R.id.title_iv_back);
        title_relate_layout = (RelativeLayout) findViewById(R.id.title_layout);
        title_tv_title = (TextView) findViewById(R.id.title_title);
        title_iv_right = (ImageView) findViewById(R.id.title_right);
        title_tv_right = (TextView) findViewById(R.id.title_tv_right);
        title_tv_back = (TextView) findViewById(R.id.title_tv_back);
        title_iv_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setFinish();
            }
        });
        title_tv_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setFinish();
            }
        });
    }

    public void setFinish() {
        finish();
    }

    public void httpGet(RequestParams params, final String type) {
        this.type = type;
        if (CheckNetwork.isNetworkAvailable(BaseActivity.this)) {
            showDia("正在加载中...");
            x.http().get(params, callback);
        } else {
            senToa("网络异常");
        }
    }

    public void httpGetJSON(final String type, RequestParams params, Map map) {
        this.type = type;
        JSONObject json = new JSONObject(map);
        params.setAsJsonContent(true);
        params.setBodyContent(json.toString());
        httpGet(params, type);
    }

    public void httpPostJSON(final String type, RequestParams params, Map map) {
        JSONObject json = new JSONObject(map);
        params.setAsJsonContent(true);
        params.setBodyContent(json.toString());
        http(params, type);
    }

    public void httpPutJSON(final String type, RequestParams params, Map map) {
        this.type = type;
        if (CheckNetwork.isNetworkAvailable(BaseActivity.this)) {
            showDia("正在加载中...");
            JSONObject json = new JSONObject(map);
            params.setAsJsonContent(true);
            params.setBodyContent(json.toString());
            x.http().request(HttpMethod.PUT, params, callback);
        } else {
            senToa("网络异常");
        }
    }

    public void httpPut(final String type, RequestParams params) {
        this.type = type;
        if (CheckNetwork.isNetworkAvailable(BaseActivity.this)) {
            showDia("正在加载中...");
            x.http().request(HttpMethod.PUT, params, callback);
        } else {
            senToa("网络异常");
        }
    }

    public void httpDelete(final String type, RequestParams params) {
        this.type = type;
        if (CheckNetwork.isNetworkAvailable(BaseActivity.this)) {
            showDia("正在加载中...");
            x.http().request(HttpMethod.DELETE, params, callback);
        } else {
            senToa("网络异常");
        }
    }

    public void httpPost(final String type, RequestParams params) {
        http(params, type);
    }

    private void http(RequestParams params, final String type) {
        this.type = type;
        if (CheckNetwork.isNetworkAvailable(BaseActivity.this)) {
            showDia("正在加载中...");
            x.http().post(params, callback);
        } else {
            senToa("网络异常");
        }
    }

    Callback.CommonCallback<String>
            callback = new Callback.CacheCallback<String>() {
        @Override
        public boolean onCache(String result) {
            return false;
        }

        @Override
        public void onSuccess(String result) {
            System.out.println("result" + result);
            if (type.equals("verify"))
                success(result, type);
            else {
//                BaseResult baseResult = JSON.parseObject(result, BaseResult.class);
//                if (baseResult.getCode() == 200)
//                    success(result, type);
//                else
//                    senToa(baseResult.getMessage());
            }
            hideDia();
        }

        @Override
        public void onError(Throwable ex, boolean isOnCallback) {
            error(ex.getMessage(), type);
            senToa("error" + ex.getMessage());
            hideDia();
        }

        @Override
        public void onCancelled(CancelledException cex) {

        }

        @Override
        public void onFinished() {

        }
    };

    public void success(String result, String type) {

    }

    public void error(String result, String type) {

    }

    public void senToa(String text) {
        Toast mToast = null;
        if (mToast == null) {
            mToast.makeText(context, text, Toast.LENGTH_LONG).show();
        }
    }

    public void senToa(@StringRes int id) {
        Toast mToast = null;
        if (mToast == null) {
            mToast.makeText(context, id, Toast.LENGTH_LONG).show();
        }
    }

    public void showDia(String str) {
        if (progressDialog == null) {
            progressDialog = new ProgressDialog(this);
            progressDialog.setProgressStyle(R.style.CustomProgressDialog);
        }
        progressDialog.setMessage(str);
        progressDialog.show();
    }

    public void hideDia() {
        try {
            if (progressDialog != null && progressDialog.isShowing()) {
                progressDialog.dismiss();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void jumpBundleActvity(Class cls, Bundle bundle) {
        Intent intent = new Intent();
        intent.putExtras(bundle);
        intent.setClass(context, cls);
        startActivity(intent);
    }

    public void jumpActvity(Class cls) {
        Intent intent = new Intent();
        intent.setClass(context, cls);
        startActivity(intent);
    }

    public void jumpActvity(Class cls, String action) {
        Intent intent = new Intent();
        if (StringUtil.isNotBlank(action))
            intent.setAction(action);
        intent.setClass(context, cls);
        startActivity(intent);
    }

    public void jumpBundleActvityforResult(Class cls, Bundle bundle, int code) {
        Intent intent = new Intent();
        if (null != bundle)
            intent.putExtras(bundle);
        intent.setClass(context, cls);
        startActivityForResult(intent, code);
    }

    public void jumpBundleActvityforResult(Class cls, Bundle bundle, int code, String action) {
        Intent intent = new Intent();
        if (StringUtil.isNotBlank(action))
            intent.setAction(action);
        if (null != bundle)
            intent.putExtras(bundle);
        intent.setClass(context, cls);
        startActivityForResult(intent, code);
    }

    public void setResultAct(Bundle bundle) {
        Intent intent = new Intent();
        intent.putExtras(bundle);
        setResult(RESULT_OK, intent);
    }

    protected boolean checkCameraPermission() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.CAMERA},
                    PermissionRequestCode.CAMERA);
            return false;
        } else {
            return true;
        }
    }

    protected boolean checkStoragePermission() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED
                || ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)
                != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this,
                    new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,
                            Manifest.permission.READ_EXTERNAL_STORAGE},
                    PermissionRequestCode.STORAGE);
            return false;
        } else {
            return true;
        }
    }

    protected class PermissionRequestCode {
        public final static int STORAGE = 20;
        public final static int CAMERA = 40;
    }

    /**
     * @param isGrant true 已授权，flase 已拒绝
     */
    protected void gotStoragePermissionResult(boolean isGrant) {
    }

    /**
     * @param isGrant true 已授权，flase 已拒绝
     */
    protected void gotCameraPermissionResult(boolean isGrant) {
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        boolean grantResult = false;
        if (grantResults.length > 0) {
            //只要有一项通过，则认为已授权
            for (int i = 0; i < grantResults.length; i++) {
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED)
                    grantResult = true;
            }
        }
        switch (requestCode) {
            case PermissionRequestCode.STORAGE:
                gotStoragePermissionResult(grantResult);
                break;
            case PermissionRequestCode.CAMERA:
                gotCameraPermissionResult(grantResult);
                break;
        }
    }
}
